package com.itheima.reggie.interceptor;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.itheima.reggie.common.EmployeeHolder;
import com.itheima.reggie.common.ResultInfo;
import com.itheima.reggie.domain.Employee;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 添加拦截器
 * @author zsk
 * @create 2022-02-28-21:56
 */
@Component//将此对象放入到配置文件中
public class LoginCheckInterceptor implements HandlerInterceptor {

    //在登陆前进行验证
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        //查看session中是否存在指定的SESSOION_EMPLOYEE
        Employee employee = (Employee) request.getSession().getAttribute("SESSION_EMPLOYEE");

        //对employee进行判断
        if (employee != null){
            //证明用户已登录
            //将当前访问用户信息放入到ThreadLocal对象中
            EmployeeHolder.set(employee);
            return true;//放行
        }else{
            //证明当前session中没有用户信息
            ResultInfo resultInfo = ResultInfo.error("NOTLOGIN");//给前端返回一个没有登陆的信息
            //转换成json数据返回给前端
            String json = new ObjectMapper().writeValueAsString(resultInfo);
            response.getWriter().write(json);

            //静止通行
            return false;
        }
    }

    //离开拦截器之前销毁ThreadLocal中存储的消息
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        //销毁ThreadLocal当前线程的消息
        EmployeeHolder.remove();
    }
}
